package com.java.jetpackdemo.room

import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
import androidx.room.migration.Migration
import androidx.sqlite.db.SupportSQLiteDatabase
import com.java.jetpackdemo.MyApplication

/**
 * 第一个参数，可以传多个实体类
 * 第二个参数：代表数据库版本,原来是1   升级为2
 */
@Database(entities = [UserBean::class], version = 2)
abstract class UserDataBase : RoomDatabase() {
    companion object {
        //更新数据库结构，增加一个字段eng_name  从1版本升级到2版本
        private val MIGRATION_1_2 = object : Migration(1, 2) {
            override fun migrate(database: SupportSQLiteDatabase) {
//                        VARCHAR(32) NOT NULL DEFAULT 'joe'  必须写，如果是bool类型就用Integer类型
                database.execSQL("ALTER TABLE UserBean ADD COLUMN eng_name TEXT NOT NULL DEFAULT 'joe'")
            }
        }

        //更新数据库结构，删除一个字段eng_name  从1版本升级到2版本  -->失败
        private val MIGRATION_2_3 = object : Migration(2, 3) {
            override fun migrate(database: SupportSQLiteDatabase) {
                database.execSQL("CREATE TABLE UserBean_t ('id' INTEGER PRIMARY KEY NOT NULL,'name' TEXT NOT NULL,'age' INTEGER NOT NULL,'sex' TEXT NOT NULL,'eng_name' TEXT NOT NULL)")
                database.execSQL("INSERT INTO UserBean_t (id,name,sex,age,eng_name) SELECT id,name,sex,age,eng_name FROM UserBean")
                database.execSQL("DROP TABLE UserBean")
                database.execSQL("ALTER TABLE UserBean_t RENAME TO UserBean")
            }
        }

        //allowMainThreadQueries:Room操作数据库默认不予许在主线程操作，这里改成允许在主线程操作
        val instance: UserDataBase
            get() = Room.databaseBuilder(
                MyApplication.instance,
                UserDataBase::class.java,
                "USER_DB"
            )
                .fallbackToDestructiveMigration()       //破坏数据库结构，会清空数据，一般不建议采用
                .addMigrations(MIGRATION_2_3)
                .allowMainThreadQueries().build()
    }

    abstract fun userDao(): UserDao


}